import React, { useState } from 'react';
import {
  View,
  StyleSheet,
  TouchableOpacity,
  Image,
  StatusBar,
  Dimensions,
  ScrollView,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { useNavigation } from '@react-navigation/native';
import { 
  ResponsiveContainer, 
  ResponsiveText,
  scale,
  Sizes
} from '../components';

// Get screen width for responsive tab width
const { width: SCREEN_WIDTH } = Dimensions.get('window');

// Tab items 
const tabItems = [
  { key: 'all', title: '全部' },
  { key: 'pending_payment', title: '待付款' },
  { key: 'pending_shipment', title: '待发货' },
  { key: 'pending_receipt', title: '待收货' },
  { key: 'pending_evaluation', title: '待评价' },
];

// 示例订单数据
const sampleOrders = [
  {
    id: 'XM12345678',
    status: 'pending_receipt',
    statusText: '配送中',
    orderTime: '2023-05-10 14:30',
    items: [
      { id: 1, name: '胡萝卜', quantity: 2, price: 36.8, image: 'https://via.placeholder.com/40/FFA500/FFFFFF?text=C' },
      { id: 2, name: '橘子', quantity: 1, price: 39.8, image: 'https://via.placeholder.com/40/FFA500/FFFFFF?text=O' },
    ],
    totalPrice: 76.6,
    deliveryFee: 5.0,
    totalItems: 2,
  }
];

const OrdersScreen: React.FC = () => {
  const [activeTab, setActiveTab] = useState('all');
  const navigation = useNavigation();

  const handleTabPress = (tabKey: string) => {
    setActiveTab(tabKey);
  };

  const handleBack = () => {
    navigation.goBack();
  };
  
  // 跳转到订单跟踪页面
  const handleTrackOrder = (orderId: string) => {
    navigation.navigate('OrderTracking' as never);
  };

  // 计算当前标签页下的订单
  const filteredOrders = activeTab === 'all' 
    ? sampleOrders 
    : sampleOrders.filter(order => order.status === activeTab);

  // 计算标签宽度
  const tabWidth = SCREEN_WIDTH / tabItems.length;

  return (
    <ResponsiveContainer statusBarStyle="dark-content" style={styles.container}>
      <StatusBar backgroundColor="#FFFFFF" barStyle="dark-content" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity onPress={handleBack} style={styles.backButton}>
          <Icon name="chevron-back" size={scale(22)} color="#000" />
        </TouchableOpacity>
        <ResponsiveText style={styles.headerTitle}>我的订单</ResponsiveText>
        <View style={styles.placeholderRight} />
      </View>

      {/* Tab navigation */}
      <View style={styles.tabContainer}>
        <View style={styles.tabRow}>
          {tabItems.map((item) => (
            <TouchableOpacity
              key={item.key}
              style={[styles.tabItem, { width: tabWidth }]}
              onPress={() => handleTabPress(item.key)}
            >
              <ResponsiveText 
                style={[
                  styles.tabText, 
                  activeTab === item.key && styles.activeTabText
                ]}
              >
                {item.title}
              </ResponsiveText>
              {activeTab === item.key && <View style={[
                styles.activeIndicator,
                item.key === 'all' && styles.shortIndicator
              ]} />}
            </TouchableOpacity>
          ))}
        </View>
      </View>

      {/* 订单列表或空状态 */}
      {filteredOrders.length > 0 ? (
        <ScrollView style={styles.ordersList} showsVerticalScrollIndicator={false}>
          {filteredOrders.map(order => (
            <View key={order.id} style={styles.orderCard}>
              <View style={styles.orderHeader}>
                <ResponsiveText style={styles.orderNumber}>订单号: {order.id}</ResponsiveText>
                <ResponsiveText style={styles.orderStatus}>{order.statusText}</ResponsiveText>
              </View>
              
              <View style={styles.orderItems}>
                {order.items.map(item => (
                  <View key={item.id} style={styles.itemRow}>
                    <Image source={{ uri: item.image }} style={styles.itemImage} />
                    <View style={styles.itemDetails}>
                      <ResponsiveText style={styles.itemName}>{item.name}</ResponsiveText>
                      <ResponsiveText style={styles.itemPrice}>¥{item.price.toFixed(1)} x {item.quantity}</ResponsiveText>
                    </View>
                  </View>
                ))}
              </View>
              
              <View style={styles.orderFooter}>
                <ResponsiveText style={styles.totalItems}>共{order.totalItems}件商品</ResponsiveText>
                <ResponsiveText style={styles.totalPrice}>
                  实付: <ResponsiveText style={styles.priceValue}>¥{order.totalPrice.toFixed(1)}</ResponsiveText>
                </ResponsiveText>
              </View>
              
              <View style={styles.actionButtons}>
                <TouchableOpacity style={styles.actionButton}>
                  <ResponsiveText style={styles.actionButtonText}>再次购买</ResponsiveText>
                </TouchableOpacity>
                <TouchableOpacity 
                  style={[styles.actionButton, styles.primaryButton]}
                  onPress={() => handleTrackOrder(order.id)}
                >
                  <ResponsiveText style={styles.primaryButtonText}>追踪订单</ResponsiveText>
                </TouchableOpacity>
              </View>
            </View>
          ))}
        </ScrollView>
      ) : (
        <View style={styles.emptyContainer}>
          <Image 
            source={{
              uri: ''
            }}
            style={styles.emptyImage}
            resizeMode="contain"
          />
          <ResponsiveText style={styles.emptyText}>抱歉, 没有找到订单哦</ResponsiveText>
        </View>
      )}
    </ResponsiveContainer>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    height: scale(50),
    paddingHorizontal: scale(15),
  },
  headerTitle: {
    fontSize: scale(16),
    fontWeight: '500',
    color: '#000000',
  },
  backButton: {
    padding: scale(5),
  },
  placeholderRight: {
    width: scale(20),
  },
  tabContainer: {
    borderBottomWidth: 1,
    borderBottomColor: '#F2F2F2',
  },
  tabRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
  },
  tabItem: {
    paddingVertical: scale(15),
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative',
  },
  tabText: {
    color: '#666666',
    fontSize: scale(14),
    textAlign: 'center',
    fontWeight: 'normal',
  },
  activeTabText: {
    color: '#333333',
    fontWeight: '500',
  },
  activeIndicator: {
    position: 'absolute',
    bottom: 0,
    height: scale(3),
    width: '16%',
    backgroundColor: '#4CAF50',
    borderRadius: scale(1.5),
  },
  shortIndicator: {
    width: '30%',
  },
  ordersList: {
    flex: 1,
    padding: scale(10),
  },
  orderCard: {
    backgroundColor: '#FFFFFF',
    borderRadius: scale(8),
    marginBottom: scale(12),
    padding: scale(12),
    borderWidth: 1,
    borderColor: '#F0F0F0',
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  orderHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingBottom: scale(10),
    borderBottomWidth: 1,
    borderBottomColor: '#F5F5F5',
  },
  orderNumber: {
    fontSize: scale(13),
    color: '#666',
  },
  orderStatus: {
    fontSize: scale(13),
    color: '#4CAF50',
    fontWeight: '500',
  },
  orderItems: {
    paddingVertical: scale(10),
  },
  itemRow: {
    flexDirection: 'row',
    marginBottom: scale(8),
  },
  itemImage: {
    width: scale(50),
    height: scale(50),
    borderRadius: scale(4),
    backgroundColor: '#F5F5F5',
  },
  itemDetails: {
    flex: 1,
    marginLeft: scale(10),
    justifyContent: 'center',
  },
  itemName: {
    fontSize: scale(14),
    color: '#333',
    marginBottom: scale(4),
  },
  itemPrice: {
    fontSize: scale(12),
    color: '#999',
  },
  orderFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: scale(10),
    borderTopWidth: 1,
    borderTopColor: '#F5F5F5',
  },
  totalItems: {
    fontSize: scale(12),
    color: '#999',
  },
  totalPrice: {
    fontSize: scale(12),
    color: '#999',
  },
  priceValue: {
    color: '#FF6B00',
    fontWeight: '500',
  },
  actionButtons: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginTop: scale(15),
  },
  actionButton: {
    paddingHorizontal: scale(15),
    paddingVertical: scale(6),
    borderRadius: scale(16),
    borderWidth: 1,
    borderColor: '#DDD',
    marginLeft: scale(10),
  },
  primaryButton: {
    backgroundColor: '#4CAF50',
    borderColor: '#4CAF50',
  },
  actionButtonText: {
    fontSize: scale(12),
    color: '#666',
  },
  primaryButtonText: {
    fontSize: scale(12),
    color: '#FFF',
    fontWeight: '500',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingBottom: '15%',
  },
  emptyImage: {
    width: scale(120),
    height: scale(120),
    tintColor: '#E0E0E0',
    marginBottom: scale(10),
  },
  emptyText: {
    color: '#999999',
    fontSize: scale(14),
  },
});

export default OrdersScreen; 